<template>
  <div class="home">
    <div class="content-box" style="padding-bottom: 1.3rem">
      <div class="padding-lr-32">
        <!--<div style="width: 100%">-->
          <!--{{itemList.files}}-->
        <!--</div>-->

        <ul class="">
          <li v-for="(item,index) in itemList" :key="index">
            <h3 class="title3 margin-bottom-10">{{item.directoryName}}{{item.mandatory==1?'(必传)':''}}</h3>

            <div v-for="(item2,index2) in item.imgList" :key="index2" class="file_item">
              <div class="prediv center">
                <img :src="item2">
              </div>
              <div class="file_options">
                <div class="btn" @click="deleteImage(index,index2)">删除</div>
              </div>
            </div>


            <div class="buttonSubmit margin-top-20" @click="chooseImage(index,item.fileLimitHbound)">
              <span>点击添加附件</span>
            </div>

          </li>
        </ul>


      </div>
    </div>

    <div class="footer-button" v-if="itemList.length!==0">
      <!--<div class="buttonSubmit" :class="{disabled:itemList[0].imgList.length===0}" @click="upload">-->
      <div class="buttonSubmit" :class="{disabled:!pass}" @click="saveAptApply">
        <span>提交申请</span>
      </div>
    </div>
  </div>



</template>

<script>
  /* eslint-disable */
  import { Indicator } from 'mint-ui';

  export default {
  name: 'Home',
  data() {
    return {
      pass:false,
      safetyNo:'',
      selected:null,
      papersnumber:'',
      itemList:[],
      list:[require('../../assets/images/12.jpg')]
    }
  },
  created(){
    this.safetyNo = this.$route.query.safetyNo || "RY_SAFETY_PROF_0099";
    this.papersnumber = this.$route.query.papersnumber || "";
    console.log(this.safetyNo );
    Indicator.open('加载中...');
    this.GetSafeDelay();
  },

  methods: {

    GetSafeDelay:function (data) {  // 安全 延期 办理
      let date = new Date().getTime().toString();
      let sign = this.$md5('SAFETYYQSQ' + date);
      let param = {
        from: '3',
        key: 'c985d190075e440a83bdcab5f0a1c792',
        sign: sign,
        requestTime: date,
        certType:'RY_SAFETY'
      };
      this.$api.post('/jimp/link.do',
          {param: JSON.stringify(param)}, response => {
          console.log(response);
          if(response.status===200 && (response.data.success || response.data.status =="200")){
            this.itemList = response.data.obj;
            this.itemList.forEach(item=>{
              item.imgList = [];
              item.files=[];
              Indicator.close();
            })
          }else {
            this.itemList = [];
            Indicator.close();
          }

        },err=>{
          Indicator.close();
        });
    },

    getRelationFileItems(fileList){
      let fileItems = [];
      if(fileList){
        for(var i=0;i<fileList.length;i++){
          let item=fileList[i];
          let fileItem = {};
          let fileIds = [];
          if (item.mandatory === '1') {
            if (item.files.length <= 0) {
              return [];
            }
            fileItem.configId = "bifile_" + item.bfileConfigId;
            item.files.forEach(child => {
              fileIds.push(child.fileId)
            });
            fileItem.fileIds = fileIds.join(",");
            fileItems.push(fileItem)
          } else {
            if (item.files.length > 0) {
              fileItem.configId = "bifile_" + item.bfileConfigId;
              item.files.forEach(child => {
                fileIds.push(child.fileId)
              });
              fileItem.fileIds = fileIds.join(",");
              fileItems.push(fileItem)
            }
          }
        }
      }
      return fileItems;
    },

    deleteImage(index,index2){
      let that = this;
      this.$bridge(function () {
        AlipayJSBridge.call('confirm', {
          message: '确定删除？',
          align:'center',
          okButton: '确定',
          cancelButton: '取消'
        },function (e) {
          if(e.ok){
            that.itemList[index].imgList.splice(index2,1);
            that.$forceUpdate();
            that.isPass()
          }
        });
      });


    },

    chooseImage(index,fileLimit){
      let that = this;
      let thisItemList = that.itemList[index];
      const limitNum = Number(fileLimit);
      if(thisItemList.imgList.length >= limitNum){
        this.$bridge(function () {
          AlipayJSBridge.call('toast', {
            content: '做多选择'+limitNum+'张',
            duration: 2000
          });
        })
      }else {
        this.$bridge(function () {
          AlipayJSBridge.call('chooseImage', {
            sourceType: ['camera', 'album'],
            count: limitNum - thisItemList.imgList.length,
          }, function (result) {
            let apFilePath =  result.apFilePaths || [];
            if (typeof apFilePath === 'string') {
              try {
                apFilePath = JSON.parse(apFilePath);
              } catch (e) {}
            }
            that.upload(index,apFilePath);

          });
        })
      }

    },

    base64(imgPath,callback){
      let image = new Image();
      image.crossOrigin = 'anonymous';
      image.onload = function() {
        let canvas = document.createElement('CANVAS');
        let context = canvas.getContext('2d');
        canvas.height = image.height;
        canvas.width = image.width;
        context.drawImage(image, 0, 0);
        try {
          let dataURL = canvas.toDataURL('image/jpeg');
          callback(dataURL)
        } catch (e) {
            console.log(e)
        }
        canvas = null;
      };
      image.src = imgPath;
    },
    uploadImage:function () {
          // 上传图片接口
          console.log(this.list)
          let that = this;
          this.list.forEach(item=>{
              that.base64(item,function (dataUrl) {
                  let date = new Date().getTime().toString();
                  let sign = that.$md5('SAFETYYQSQ' + date);
                  let param ={
                      from: '3',
                      key: 'ca35f5107701478fb933d249cf10055a',
                      sign: sign,
                      requestTime: date,
                      files:dataUrl
                  };
                  console.log(param)
                  that.$api.post('/jimp/link.do',
                      {param:JSON.stringify(param)}, response => {
                          if(response.status===200 && (response.data.success || response.data.status == "200")){
                              thisItemList.imgList.push(item);
                              thisItemList.files.push(response.data.obj[0]);
                              that.$forceUpdate();
                              that.isPass()
                          }
                      });
              });
          })

      },

    upload:function (index,apFilePath) {
        // 上传图片接口
      let that = this;
      let thisItemList = that.itemList[index];
      apFilePath.forEach(item=>{
         that.base64(item,function (dataUrl) {
             let date = new Date().getTime().toString();
             let sign = that.$md5('SAFETYYQSQ' + date);
             let param ={
                 from: '3',
                 key: 'ca35f5107701478fb933d249cf10055a',
                 sign: sign,
                 requestTime: date,
                 files:dataUrl
             };
             that.$api.post('/jimp/link.do',
                 {param:JSON.stringify(param)}, response => {
                 if(response.status===200 && (response.data.success || response.data.status == "200")){
                     thisItemList.imgList.push(item);
                     thisItemList.files.push(response.data.obj[0])
                     that.$forceUpdate();
                     that.isPass()
                 }
          });
       });
      })
    },

    isPass(){
      this.itemList.forEach(item=>{
        if(item.mandatory === '1' && item.imgList.length ===0){
          this.pass = false;
          return;
        }else  {
          this.pass = true;
        }
      })
    },

    saveAptApply(){
      if(!this.pass)return;
      Indicator.open('正在提交...');
      let _this = this;
        let date = new Date().getTime().toString();
        let sign = this.$md5('SAFETYYQSQ' + date);
         let param ={
         from: '3',
         key: '3d9865e0e0b14ca784127d68e9c160b0',
         sign: sign,
         requestTime: date,
         certNo: this.safetyNo,
         certType: 'RY_SAFETY',
         applyType: 'RY_YWSQLB_YX',
         cardNo:_this.papersnumber,
        };
        var fileList=this.itemList;
        var relationFileItems = this.getRelationFileItems(fileList);
        if (!relationFileItems || relationFileItems<=0){
            console.log("缺少附件");
            return;
        }

        relationFileItems.forEach(item=>{
            param[item.configId]=item.fileIds;
        });

      this.$api.post('/jimp/link.do', {param: JSON.stringify(param)}, response => {
        console.log(response);
        Indicator.close();
        if(response.status==='200' && (response.data.result || response.data.code ==="200")){
          this.$bridge(function () {
            AlipayJSBridge.call('toast', {
              content: '提交成功，请到江西住建云个人服务平台查看',type: 'success',duration: 2000
            },function () {
              _this.$router.go(-1);
            })
          })

        }else {
          Indicator.close();
          alert('网络连接成功但提交失败');
          _this.$router.go(-1);
        }

      },err=>{
        Indicator.close();
        alert('网络连接错误');
        _this.$router.go(-1);
      });
    }

  }
}
</script>
<style lang="less" scoped>

</style>
